<template>
  <div class="login-container">
    <!-- 登录 -->
    <div class="login-wrap">
      <div class="login">
        <div class="loginform">
          <ul class="tab clearFix">
            <li>
              <a href="##" style="border-right: 0;">扫描登录</a>
            </li>
            <li>
              <a href="##" class="current">账户登录</a>
            </li>
          </ul>

          <div class="content">
            <form @submit.prevent="loginingUser">
              <div class="input-text clearFix">
                <span></span>
                <input type="text" placeholder="邮箱/用户名/手机号" v-model="userPhone">
              </div>
              <div class="input-text clearFix">
                <span class="pwd"></span>
                <input type="text" placeholder="请输入密码" v-model="userPassword">
              </div>
              <div class="setting clearFix">
                <label class="checkbox inline">
                  <input name="m1" type="checkbox" value="2" checked="">
                  自动登录
                </label>
                <span class="forget">忘记密码？</span>
              </div>
              <button type="submit" class="btn">登&nbsp;&nbsp;录</button>
            </form>


            <div class="call clearFix">
              <ul>
                <li><img src="./images/qq.png" alt=""></li>
                <li><img src="./images/sina.png" alt=""></li>
                <li><img src="./images/ali.png" alt=""></li>
                <li><img src="./images/weixin.png" alt=""></li>
              </ul>
              <router-link class="register" to="/register">立即注册</router-link>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 底部 -->
    <div class="copyright">
      <ul>
        <li>关于我们</li>
        <li>联系我们</li>
        <li>联系客服</li>
        <li>商家入驻</li>
        <li>营销中心</li>
        <li>手机尚品汇</li>
        <li>销售联盟</li>
        <li>尚品汇社区</li>
      </ul>
      <div class="address">地址：北京市昌平区宏福科技园综合楼6层</div>
      <div class="beian">京ICP备19006430号
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations, mapState } from 'vuex';
import { getUUID } from '@/utils/uuid_token'
export default {
  name: 'LoginIndex',
  data() {
    return {
      userPhone: '',
      userPassword: '',
      randomUser: null // 用来保存当前抽取的用户名

    }
  },
  computed: {
    ...mapState('userList', ['allUser', 'loginedAllUser', 'loginUser'])
  },
  methods: {
    ...mapMutations('userList', ['updateLoginUser']),
    ...mapActions('userList', ['setLogin']),
    //随机生成用户名
    getRandomUser() {
      // 获取本地存储中的数组
      let arr = JSON.parse(localStorage.getItem('users')) || [];

      // 如果数组为空，提示没有更多用户名
      if (arr.length === 0) {
        alert("没有更多用户了");
        return;
      }

      // 随机选择一个索引
      const randomIndex = Math.floor(Math.random() * arr.length);

      // 抽取用户名
      this.randomUser = arr[randomIndex];
      console.log('打印一下变化前的arr' + arr);
      // 删除抽取的用户名
      // arr.splice(randomIndex, 1);  // 只删除一个用户名
      console.log('打印一下变化后的arr' + arr);

    },
    //点击登录
    async loginingUser() {
      console.log('打印一下login页面的参数：');

      console.log(this.$route.query.redirect);
      // 手机号和密码前置校验
      const phoneReg = /^1[3-9]\d{9}$/; // 简单判断是否是合法手机号
      const passwordReg = /^[a-zA-Z0-9]{6,18}$/; // 密码6-20位，仅限数字和字母

      if (!this.userPhone.trim()) {
        return this.$message.error('请输入手机号');
      }
      if (!phoneReg.test(this.userPhone)) {
        return this.$message.error('手机号格式不正确');
      }

      if (!this.userPassword.trim()) {
        return this.$message.error('请输入密码');
      }
      if (!passwordReg.test(this.userPassword)) {
        return this.$message.error('密码必须为6-20位的字母或数字');
      }
      //避免重复登录相同账号
      if (this.userPhone == this.loginUser.userPhone) {
        return this.$message.error('请勿重复登录相同账号！');
      }
      if (!this.userPhone.trim()) {
        return this.$message.error('请输入数字');
      }
      //some()方法返回一个布尔值，判断登录的号码是否已经注册过
      let existsPhone = this.allUser.some(user => user.phone == this.userPhone);
      //

      if (existsPhone) {

        //把登录的用户手机号和注册过的手机号做比较，取出注册过的登录号
        let user = this.allUser.find(userItem => userItem.phone === this.userPhone);
        console.log('输入密码:', this.userPassword);
        console.log('注册密码:', user.password);
        console.log('比较结果:', user.password === this.userPassword);

        //判断输入的密码是否和注册时的密码相等
        if (user.password === this.userPassword) {

          //existsloginedPhone 为布尔值： 判断正在登录的用户是否之前已经登录过
          let existsloginedPhone = this.loginedAllUser.some(userItem => userItem.userPhone == this.userPhone);

          if (existsloginedPhone) {
            //取出正在登录的账号是否之前已经登录过有username
            console.log('之前登录过');

            let existsLoginedUser = this.loginedAllUser.find(user => user.userPhone == this.userPhone);
            //直接把之前登陆过存储的信息再登录一下就可以，不用再随机姓名了
            this.setLogin(existsLoginedUser)
          } else {
            console.log('未登录过');

            //调用随机生成用户名
            await this.getRandomUser()
            let params = {
              userPhone: this.userPhone,
              userPassword: this.userPassword,
              token: getUUID(),//模拟token登录
              username: this.randomUser
            }
            //调用登录仓库里面的方法,存储登录用户信息
            this.setLogin(params)
            // 过滤掉在 LOGINEDALLUSER 中已经存在的 username
            let filteredArr = JSON.parse(localStorage.getItem('users')).filter(name => {
              return !this.loginedAllUser.some(user => user.username === name);
            });
            localStorage.setItem('users', JSON.stringify(filteredArr));
          }

          this.$message.success('恭喜您登录成功！');
          //登录的路由组件：看路由当中是否包含query参数，有：跳转到query参数指定的路由，没有则跳转首页
          const toPath = this.$route.query.redirect || '/home'
          this.$router.push(toPath)
        } else {
          this.$message.error('对不起，登录密码错误')
        }
      } else {
        this.$message.error('账号未注册，即将跳转注册页')
        //跳转到注册页面
        this.$router.push('/register')
      }
    }
  },
  mounted() {
    // 初始化时将用户数组保存到本地存储
    if (!localStorage.getItem('users')) {
      let arr = ['小米', 'admin', '小白', '祝贴', '小美'];
      localStorage.setItem('users', JSON.stringify(arr));
    }
  },
  updated() {
    console.log('打印一下成功登录用户：');
    console.log('this.$store.state.userList.loginUser');
  }
}
</script>

<style lang="less" scoped>
.login-container {
  .login-wrap {
    height: 487px;
    background-color: #e93854;

    .login {
      width: 1200px;
      height: 487px;
      margin: 0 auto;
      background: url(./images/loginbg.png) no-repeat;
    }

    .loginform {
      width: 420px;
      height: 406px;
      box-sizing: border-box;
      background: #fff;
      float: right;
      top: 45px;
      position: relative;
      padding: 20px;

      .tab {

        li {
          width: 50%;
          float: left;
          text-align: center;

          a {
            width: 100%;
            display: block;
            height: 50px;
            line-height: 50px;
            font-size: 20px;
            font-weight: 700;
            color: #333;
            border: 1px solid #ddd;
            box-sizing: border-box;
            text-decoration: none;

          }

          .current {
            border-bottom: none;
            border-top-color: #28a3ef;
            color: #e1251b;
          }
        }
      }

      .content {
        width: 380px;
        height: 316px;
        box-sizing: border-box;
        border: 1px solid #ddd;
        border-top: none;
        padding: 18px;

        form {
          margin: 15px 0 18px 0;
          font-size: 12px;
          line-height: 18px;

          .input-text {
            margin-bottom: 16px;

            span {
              float: left;
              width: 37px;
              height: 32px;
              border: 1px solid #ccc;
              background: url(../../assets/images/icons.png) no-repeat -10px -201px;
              box-sizing: border-box;
              border-radius: 2px 0 0 2px;
            }

            .pwd {
              background-position: -72px -201px;
            }

            input {
              width: 302px;
              height: 32px;
              box-sizing: border-box;
              border: 1px solid #ccc;
              border-left: none;
              float: left;
              padding-top: 6px;
              padding-bottom: 6px;
              font-size: 14px;
              line-height: 22px;
              padding-right: 8px;
              padding-left: 8px;

              border-radius: 0 2px 2px 0;
              outline: none;
            }
          }

          .setting {
            label {
              float: left;
            }

            .forget {
              float: right;
            }
          }

          .btn {
            background-color: #e1251b;
            padding: 6px;
            border-radius: 0;
            font-size: 16px;
            font-family: 微软雅黑;
            word-spacing: 4px;
            border: 1px solid #e1251b;
            color: #fff;
            width: 100%;
            height: 36px;
            margin-top: 25px;
            outline: none;
          }
        }

        .call {
          margin-top: 30px;

          ul {
            float: left;

            li {
              float: left;
              margin-right: 5px;
            }
          }

          .register {
            float: right;
            font-size: 15px;
            line-height: 38px;
          }

          .register:hover {
            color: #4cb9fc;
            text-decoration: underline;
          }
        }

      }
    }
  }

  .copyright {
    width: 1200px;
    margin: 0 auto;
    text-align: center;
    line-height: 24px;

    ul {
      li {
        display: inline-block;
        border-right: 1px solid #e4e4e4;
        padding: 0 20px;
        margin: 15px 0;
      }
    }
  }

}
</style>